package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxVndCheckDetails;
import com.adk.backend.entity.LxVndCheckList;
import com.adk.backend.entity.LxVndList;
import com.adk.backend.service.SpssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SPSS（供应商对账）控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/spss")
public class SpssController {
    
    @Autowired
    private SpssService spssService;
    
    /**
     * 获取供应商列表（用于SPSS）
     */
    @RequiresPermission("view")
    @GetMapping("/vnd-list")
    public Result<List<LxVndList>> getVndListForSpss(@RequestParam(required = false) Integer type) {
        List<LxVndList> result = spssService.getVndListForSpss(type);
        return Result.success(result);
    }
    
    /**
     * 获取供应商对账列表
     */
    @RequiresPermission("view")
    @GetMapping("/vnd-check-list")
    public Result<List<Map<String, Object>>> getVndCheckList(@RequestParam Long vndId) {
        List<Map<String, Object>> result = spssService.getVndCheckList(vndId);
        return Result.success(result);
    }
    
    /**
     * 获取对账详情列表
     */
    @RequiresPermission("view")
    @GetMapping("/vnd-check-details")
    public Result<List<LxVndCheckDetails>> getVndCheckDetails(@RequestParam Long vclId) {
        List<LxVndCheckDetails> result = spssService.getVndCheckDetails(vclId);
        return Result.success(result);
    }
    
    /**
     * 获取对账列表信息（带供应商名称和月份）
     */
    @RequiresPermission("view")
    @GetMapping("/vnd-check-list-info")
    public Result<Map<String, Object>> getVndCheckListInfo(@RequestParam Long vclId) {
        Map<String, Object> result = spssService.getVndCheckListInfo(vclId);
        return Result.success(result);
    }
    
    /**
     * 保存对账详情（新增或更新）
     */
    @RequiresPermission("edit")
    @PostMapping("/vnd-check-details/save")
    public Result<Boolean> saveVndCheckDetails(@RequestBody LxVndCheckDetails details, HttpServletRequest request) {
        try {
            Integer userId = ((Long) request.getAttribute("userId")).intValue();
            boolean success = spssService.saveVndCheckDetails(details, userId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("保存失败，可能该订单已确认");
            }
        } catch (Exception e) {
            log.error("保存对账详情失败", e);
            return Result.error("保存对账详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除对账详情
     */
    @RequiresPermission("edit")
    @PostMapping("/vnd-check-details/delete")
    public Result<Boolean> deleteVndCheckDetails(@RequestParam Long id) {
        try {
            boolean success = spssService.deleteVndCheckDetails(id);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("删除失败，可能该订单已确认");
            }
        } catch (Exception e) {
            log.error("删除对账详情失败", e);
            return Result.error("删除对账详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 锁定/解锁对账详情
     */
    @RequiresPermission("edit")
    @PostMapping("/vnd-check-details/lock")
    public Result<Boolean> lockVndCheckDetails(@RequestParam Long id, @RequestParam Boolean lock) {
        try {
            boolean success = spssService.lockVndCheckDetails(id, lock);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("锁定/解锁对账详情失败", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新对账列表状态
     */
    @RequiresPermission("edit")
    @PostMapping("/vnd-check-list/update-status")
    public Result<Boolean> updateVndCheckListStatus(
            @RequestParam Long id,
            @RequestParam Integer status,
            @RequestParam(required = false) BigDecimal paidAmount,
            HttpServletRequest request) {
        try {
            Integer userId = ((Long) request.getAttribute("userId")).intValue();
            boolean success = spssService.updateVndCheckListStatus(id, status, paidAmount, userId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新对账列表状态失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建对账月份
     */
    @RequiresPermission("edit")
    @PostMapping("/vnd-check-list/create")
    public Result<LxVndCheckList> createVndCheckList(
            @RequestParam Long vndId,
            @RequestParam String fMonth,
            HttpServletRequest request) {
        try {
            Integer userId = ((Long) request.getAttribute("userId")).intValue();
            LxVndCheckList result = spssService.createVndCheckList(vndId, fMonth, userId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("创建对账月份失败", e);
            return Result.error("创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查对账月份是否存在
     */
    @RequiresPermission("view")
    @GetMapping("/vnd-check-list/check-exists")
    public Result<Boolean> checkVndCheckListExists(
            @RequestParam Long vndId,
            @RequestParam String fMonth) {
        boolean exists = spssService.checkVndCheckListExists(vndId, fMonth);
        return Result.success(exists);
    }
    
    /**
     * 导入Excel文件
     */
    @RequiresPermission("edit")
    @PostMapping("/import-excel")
    public Result<Map<String, Object>> importExcel(
            @RequestParam Long vclId,
            @RequestParam Integer type,
            @RequestParam("file") org.springframework.web.multipart.MultipartFile file,
            HttpServletRequest request) {
        try {
            Integer userId = ((Long) request.getAttribute("userId")).intValue();
            Map<String, Object> result = spssService.importExcel(vclId, type, file, userId);
            if ((Boolean) result.get("success")) {
                return Result.success(result);
            } else {
                return Result.error((String) result.get("message"));
            }
        } catch (Exception e) {
            log.error("导入Excel失败", e);
            return Result.error("导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取供应商月度统计数据
     */
    @RequiresPermission("view")
    @GetMapping("/vnd-monthly-statistics")
    public Result<Map<String, Object>> getVndMonthlyStatistics(
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer year) {
        List<Map<String, Object>> statistics = spssService.getVndMonthlyStatistics(type, year);
        
        // 组织数据：按供应商分组，然后按月份组织
        Map<Long, Map<String, Object>> vndMap = new HashMap<>();
        int currentMonth = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH) + 1;
        int currentYear = year != null ? year : java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);
        
        for (Map<String, Object> stat : statistics) {
            Long vndId = ((Number) stat.get("vnd_id")).longValue();
            Map<String, Object> vndData = vndMap.get(vndId);
            if (vndData == null) {
                vndData = new HashMap<>();
                vndData.put("vndId", vndId);
                vndData.put("type", stat.get("type"));
                vndData.put("vndName", stat.get("vnd_name"));
                vndData.put("months", new HashMap<String, Map<String, Object>>());
                vndData.put("totalBillAmount", BigDecimal.ZERO);
                vndData.put("totalPaidAmount", BigDecimal.ZERO);
                vndMap.put(vndId, vndData);
            }
            
            @SuppressWarnings("unchecked")
            Map<String, Map<String, Object>> months = (Map<String, Map<String, Object>>) vndData.get("months");
            String monthKey = (String) stat.get("month_key");
            Map<String, Object> monthData = new HashMap<>();
            monthData.put("billAmount", stat.get("bill_amount"));
            monthData.put("paidAmount", stat.get("paid_amount"));
            monthData.put("unpaidAmount", stat.get("unpaid_amount"));
            months.put(monthKey, monthData);
            
            // 累计总金额
            BigDecimal billAmount = (BigDecimal) stat.get("bill_amount");
            BigDecimal paidAmount = (BigDecimal) stat.get("paid_amount");
            vndData.put("totalBillAmount", ((BigDecimal) vndData.get("totalBillAmount")).add(billAmount));
            vndData.put("totalPaidAmount", ((BigDecimal) vndData.get("totalPaidAmount")).add(paidAmount));
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("statistics", new ArrayList<>(vndMap.values()));
        result.put("currentYear", currentYear);
        result.put("currentMonth", currentMonth);
        
        return Result.success(result);
    }
}
